\chapter{Feature}

\section{Shared Preferences}

In order to maintain the user session, we store the user's id and email in the \textsf{SharedPreferences}. The SharedPreferences class provides a general framework that allows us to save and retrieve persistent key-value pairs of primitive data types. We used them to save two strings. This data persist across user sessions, even if the application is closed or killed. To get a SharedPreferences object for our application, we used \textsf{getSharedPreferences()}: this method allows us to use multiple preferences files identified by name, which we specify with as parameter. When an user perform the login, we write his id and email in the SharedPreferences using an Editor, like we show in the following code snippet:
\begin{lstlisting}
SharedPreferences sharedPref = getActivity().getSharedPreferences(getString(R.string.logged_user_prefs),
								Context.MODE_PRIVATE);

SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(getString(R.string.logged_user_id), user.getSid());
editor.putString(getString(R.string.logged_user_email), email);
editor.commit();
editor.clear();
\end{lstlisting}
The name of this SharedPreferences is in the string \textsf{R.string.logged\_user\_prefs}, and with other two strings identifier we are able to retrieve the id and email later. It's always good practice to call \textsf{clear()} on the editor after committing the values.

\section{Thread}

In Android, the system guards against applications that are insufficiently responsive for a period of time by displaying a dialog that says your app has stopped responding. In any situation in which the app performs a potentially lengthy operation, it's good practice to not perform the work on the UI thread, but instead create a worker thread and do most of the work there. We used \textsf{AsyncTask} and \textsf{Service} to achieve this goal.

\subsection{AsyncTask}
The most effective way to create a worker thread for longer operations is with the \textsf{AsyncTask} class. We created classes which extend AsyncTask and implement the doInBackground() method to perform the work. Every time we need to perform a call to an Endpoint to retrieve some data from the server, we used AsynTask. For example, after the login, we retrieve the user's info with the UserEndpoint in an AsyncTask.

\begin{figure}[H]
\centering
\begin{minipage}{0.45\textwidth}
\centering
\includegraphics[scale=0.4]{images/login-fragment}
\end{minipage}\hfill
\begin{minipage}{0.45\textwidth}
\centering
\includegraphics[scale=0.4]{images/login-loading}
\end{minipage}
\caption{User Login Fragment}
\end{figure}

\begin{lstlisting}
public class UserLoginTask extends AsyncTask<Void, Void, TBUser> {

	@Override
	protected void onPreExecute() {
		/* show the progress dialog */
	}

	@Override
	protected TBUser doInBackground(Void... params) {

		Authenticationendpoint.Builder authEndBuilder = new Authenticationendpoint.Builder(
				AndroidHttp.newCompatibleTransport(), new JacksonFactory(),
				new HttpRequestInitializer() {
					public void initialize(HttpRequest httpRequest) {
					}
				});

		authEndpoint = CloudEndpointUtils.updateBuilder(authEndBuilder).build();
				
		String passHash = Hasher.hash(password);
		TBUser user;
		try {
			user = authEndpoint.checkCredentials(passHash, email).execute();
		} catch (IOException e) {
			/* catch */
		}

		return user;
	}

	@Override
	protected void onPostExecute(final TBUser user) {		
		if (user != null) {
			/* Save SharedPreferences and start PersonalAreaActivity */
		} else {
			/* notify error to the user */
		}
	}
}
\end{lstlisting}

In the above code snippet is shown how we use AsyncTask. In the \textsf{onPreExecute()} method we create the progress dialog and show it to the user. In the \textsf{doInBackground()} method we initialize the Endpoint and make the call. As a result, we return the user to the \textsf{onPostExecute()} method. This method verifies if the user does exist: if so, we save his id and email and start the PersonalAreaActivity; otherwise, we show to the user an error.

\subsection{Service}

A \textsf{Service} is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application.

We created a class which extends Service and we overrode some callback methods that handle key aspects of the service lifecycle, such as \textsf{onStartCommand()}, \textsf{onCreate()} and \textsf{onDestroy()}.
We used Service for performing some task of our application, for example for the correction of a test. When a user complete a test, a \textsf{Toast} informs that the test is under connection and that the user will receive a notification once the test has been corrected. Now, even if the user closes the app or switches to another, the Service will continue working. When the correction is finished, a notification is send and shown in the notification bar. If the user click on it, a new activity show the result of the test and the right answers.

\begin{figure}[H]
\centering
\begin{minipage}{0.45\textwidth}
\centering
\includegraphics[scale=0.4]{images/test-correcting}
\end{minipage}\hfill
\begin{minipage}{0.45\textwidth}
\centering
\includegraphics[scale=0.4]{images/test-notification}
\end{minipage}
\caption{When the Service starts a Toast is shown, and when it finishes a Notification appears.}
\end{figure}

\begin{lstlisting}
public class CorrectTestService extends Service {
	/* ... */
	private final class ServiceHandler extends Handler {
		public ServiceHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			correctTest();
			sendNotification();
			stopSelf();
		}
	}

	@Override
	public void onCreate() {
		HandlerThread thread = new HandlerThread("ServiceStartArguments",
				Process.THREAD_PRIORITY_BACKGROUND);
		thread.start();
		/* ... */
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Toast.makeText(this,
				"Test inviato. Appena sara' corretto, riceverai una notifica.",
				Toast.LENGTH_LONG).show();
		/* ... */
		return START_STICKY;
	}
}
\end{lstlisting}

\section{Location Services and Geofences}

In order to make our application location-aware, we follow the \href{developer.android.com/training/location/index.html}{\color{blue}tutorial} on android developers web site. The new Location Services API available in Google Play Services facilitates adding location tracking and geofencing features. From the \textsf{LocationActivity} class a user can "geotag" himself, if GPS is enabled. Once he has been located, he can choose to find near users. When the user make this choice, two action are performed in an AsyncTAsk:

\begin{description}
\item[Creation of a Geofence] We create a the user's \textsf{Geofence}, which represents an area of 500 meters in which the user is located. The Geofence is sent to our server, where is possible to store in the database a Geofence entity equal to the one on the android client.
\item[Download of all the Geofences] We get all the Geofences on the server, selecting only the ones in a radius of 500 meters from the logged user, which represent all the users who perfomed the "geotag". We show to the user all the user selected and we give him the possibility to wrote a message to them even if they are not friends. On server side, every 30 minutes all the geofences are deleted, in order to do not show geofences that are obsolete.
\end{description}

The user now can choose to activate the "update notification", in order to be notified if new users became near. This is made through the \textsf{NearUserUpdateService}, a Service class that runs in background even if the app is closed. Every ten minutes the Service class makes an asynchronous call with an Endpoint to collect all the Geofences on the server. Then it updates the geofences on the client side and, in case someone is near, send a notification to the user. If the user clicks on this notification, a list of all the users which are now near is shown. If the user want to stop these updates, he need to return on the LocationActivity and disable them. To save this preference, we used once again the SharedPreferences. We save the \textsf{Intent} of the update service, since it extends the \textsf{Parcelable} class, in the SharedPreferences and when the user decides to not receive the updates any more, we take it and stop the intent. Once destroyed, we delete it also from the Preferences.

\section{Open app from web link}

Since during registration and password resetting, an email is sent to the user. The link contained in the email redirect the user to the web application and the user can complete is action. If an user register to our app from a mobile device, it is likely that he will also receive the email on his device. We want our app to be able to react to this link and give the possibility to the user to complete registration and password resetting from the app. Android apps have the ability to interact with the network stack and launch an app according to known patterns in an URI. This is achieved through \textsf{Intent}, specified in the app \textsf{Manifest}. The most common use is to catch all schemes that have a specific name. We put this code into the activity in the manifest which handle the intent: 

\begin{lstlisting}
<intent-filter>
	<action android:name="android.intent.action.VIEW" ></action>
	<category android:name="android.intent.category.DEFAULT" ></category>
	<category android:name="android.intent.category.BROWSABLE" ></category>
	<data
		android:host="tb-simulator.appspot.com"
		android:scheme="http" >
	</data>
</intent-filter>
\end{lstlisting}

In this way all the link with the link of our web site is handled by the app, on mobile devices with the app installed. In future, we can also handle every possible link existing for the web application.

\begin{figure}[H]
\centering
\begin{minipage}{0.45\textwidth}
\centering
\includegraphics[scale=0.3]{images/registration-emailsent}
\end{minipage}\hfill
\begin{minipage}{0.45\textwidth}
\centering
\includegraphics[scale=0.3]{images/registration-intentselection}
\end{minipage}
\caption{An email is sent to the user after registration, the app is able to handle the link thanks to an intent.}
\end{figure}

\begin{figure}[H]
\centering
\begin{minipage}{0.45\textwidth}
\centering
\includegraphics[scale=0.3]{images/registration-confirm}
\end{minipage}\hfill
\begin{minipage}{0.45\textwidth}
\centering
\includegraphics[scale=0.3]{images/registration-confirmed}
\end{minipage}
\caption{The user is redirected to the app, he confirm the registration and now he can perform login.}
\end{figure}





\section{External Service and API}

In this section we focus on the value we tried to add on our application by interacting with other online services through their API.
First of all is important to say that we faces to Test Simulator Online as a complete external service, indeed we published its API with the technologies described before.
Test Simulator Online is both an endpoint for our calls and a passage to other externals services that cannot be accessed directly from a mobile context.

\subsection{BlobStore Service}
The most significant example of these is the Blobstore service offered by Google.
This service make possible bid data storage in a specific environment, linked with proper entities with the Big Table Datastore. All the facilities of this service pass through a single class calle BlobStoreService with create, upload, and serve file and image.
What is impossible to follow by a mobile access point is the manage of the upload sessions, required by the BlobStore Service to provide file uploading. For this reason we built up a servlet structure which hide the Blob Store service to the Android client and make possible to interact with such system with standard http without caring about upload urls handling.

\subsection{Facebook API}

We exploit the Facebook Open Graph Api to make direct access to our application both mobile and online. Users can login, publish and share their activities in our system and discover which of their friends are logged too.

To build the internal representation on Facebook access point we uses the EasyFacebookSDK for Android. This framework simplify a lot the commons interaction with OpenGraph by establish some good practises to access the user content in the Social Network. 

Each Interaction Types with Facebook is handled with a specific activity. This make possible to separate  each task, a detail that became important if we consider each external call through the internet connection as a possible standpoint for our application. The interaction with both Facebook and our online reference are make asynchronously for the explained reasons.

Facebook interaction is just one step in social networking linking for our application. We understood the importance and the opportunity to collect users from this resources.


